<template>
  <el-dialog
    :model-value="visible"
    title="管理关系"
    width="600px"
    @update:modelValue="$emit('update:visible', $event)"
    @open="onDialogOpen"
  >
    <el-form :model="form" ref="formRef" :rules="rules" label-position="top">
      <el-alert type="info" :closable="false" style="margin-bottom: 20px;">
        为当前成员 <strong style="color: #409eff;">{{ currentPersonName }}</strong> 添加一个新关系。
      </el-alert>
      <el-form-item label="选择关系类型" prop="relationTypeId">
        <el-select v-model="form.relationTypeId" placeholder="请选择关系" style="width: 100%;">
          <el-option
            v-for="item in relationTypes"
            :key="item.itemId"
            :label="item.itemName"
            :value="item.itemId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="选择关联的成员" prop="personId2">
        <el-select v-model="form.personId2" filterable placeholder="搜索并选择成员" style="width: 100%;">
          <el-option
            v-for="person in availablePersons"
            :key="person.personId"
            :label="`${person.name} (ID: ${person.personId})`"
            :value="person.personId"
          />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="$emit('update:visible', false)">取消</el-button>
      <el-button type="primary" @click="handleSubmit" :loading="loading">保存关系</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue';
import { ElMessage, type FormInstance, type FormRules } from 'element-plus';
import { addRelationApi } from '@/api/person';
import { getPersonsByFamilyTreeIdApi } from '@/api/family'; // 【修正】导入正确的API
import { getCommonDictApi } from '@/api/common';
import type { AddRelationRequest, Person, CommonType } from '@/types/api';

const props = defineProps<{
  visible: boolean;
  currentPersonId: number;
  currentPersonName: string;
  familyId: number; // 【新增】接收家谱ID
}>();
const emit = defineEmits(['update:visible', 'success']);

const formRef = ref<FormInstance>();
const loading = ref(false);

const form = reactive<AddRelationRequest>({
  personId1: props.currentPersonId,
  personId2: null,
  relationTypeId: null,
});

const relationTypes = ref<CommonType[]>([]);
const familyPersons = ref<Person[]>([]); // 【修正】只存储当前家谱的成员

// 过滤掉当前成员自己
const availablePersons = computed(() =>
  familyPersons.value.filter(p => p.personId !== props.currentPersonId)
);

const rules: FormRules = {
  relationTypeId: [{ required: true, message: '请选择关系类型', trigger: 'change' }],
  personId2: [{ required: true, message: '请选择关联的成员', trigger: 'change' }],
};

// 当对话框打开时，加载下拉框数据
const onDialogOpen = async () => {
  form.personId1 = props.currentPersonId;
  form.personId2 = null;
  form.relationTypeId = null;

  // 仅在数据为空时加载，避免重复请求
  if (relationTypes.value.length === 0) {
    relationTypes.value = await getCommonDictApi(1);
  }
  // 【修正】每次打开都重新获取当前家谱的成员列表，以保证数据最新
  familyPersons.value = await getPersonsByFamilyTreeIdApi(props.familyId);
};

const handleSubmit = async () => {
  if (!formRef.value) return;
  await formRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true;
      try {
        await addRelationApi(form);
        ElMessage.success("关系添加成功");
        emit('success');
        emit('update:visible', false);
      } finally {
        loading.value = false;
      }
    }
  });
};
</script>
